//
//  QuotePrintController.m
//  example
//
//  Created by li on 2018/12/4.
//  Copyright © 2018 li. All rights reserved.
//

#import "QuotePrintController.h"
#import "HLPrinter.h"
#import "HLBLEManager.h"
#import "NSString+Length.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "PrintPopWindow.h"

static int TOTAL = 48;//这里是根据你的纸张宽度试验出来的一个合适的总字数


@interface QuotePrintController ()
{
    BOOL isConnection;
}

@property (nonatomic, strong) HLPrinter *printer;
@property (nonatomic, strong) NSMutableArray *deviceArray;  /** 蓝牙设备个数 */

@property (nonatomic, strong) CBCharacteristic *chatacter;  /**< 可写入数据的特性 */
@property (nonatomic, strong) CBPeripheral *perpheral;
@property (nonatomic, strong) NSMutableArray *infos;  /**< 详情数组 */

@property (nonatomic, strong) PrintPopWindow *popWindow;
@property (nonatomic, strong) UITextField *pageTextField;

@property (nonatomic, strong) UILabel *tipsLabel;

@end

@implementation QuotePrintController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"打印";
    [self addTipsLabel];
    
    _printer = [[HLPrinter alloc] init];
    _deviceArray = [[NSMutableArray alloc] init];
    [self searchPrinter];
    
    UIImage *image = [UIImage imageNamed:@"public_backArrow"];
    
    UIBarButtonItem *backItm = [[UIBarButtonItem alloc] initWithImage:image style:(UIBarButtonItemStylePlain) target:self action:@selector(pop)];
    self.navigationItem.leftBarButtonItem = backItm;
}

- (void)addTipsLabel{
    _tipsLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, kScreenW - 20 * 2, 60)];
    _tipsLabel.centerY = self.view.centerY - 80;
    _tipsLabel.text = @"请打开手机蓝牙，并打开蓝牙打印机开关";
    _tipsLabel.font = [UIFont systemFontOfSize:15];
    _tipsLabel.textColor = [UIColor redColor];
    _tipsLabel.numberOfLines = 0;
    _tipsLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_tipsLabel];
}

- (void)addPrintOverView{
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake((self.view.width-100)/2, self.view.height/4, 100, 100)];
    imageView.image = [UIImage imageNamed:@"printlodaing_03.png"];
    
    UILabel *dayinLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, imageView.maxY+10, self.view.width, 20)];
    dayinLabel.text = @"打印中";
    dayinLabel.textAlignment = NSTextAlignmentCenter;
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(20, dayinLabel.maxY + 80, self.view.width-40, 44)];
    [button setTitle:@"完成打印" forState:UIControlStateNormal];
    button.backgroundColor = kMainColor;
    button.layer.cornerRadius = 6;
    [button addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, button.maxY+10, button.width, 60)];
    label.text = @"打印时请勿点击按钮或退出页面，否则将会中断打印！打印完成后，点击“完成打印”继续操作！";
    label.font = [UIFont systemFontOfSize:15];
    label.textColor = [UIColor redColor];
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    
    [self.view addSubview:imageView];
    [self.view addSubview:dayinLabel];
    [self.view addSubview:button];
    [self.view addSubview:label];
}

- (void)pop{
    [self bleakBlueTooth];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 打印

-(void)searchPrinter{
    //获取打印机列表数据
    HLBLEManager *manager = [HLBLEManager sharedInstance];
    manager.stateUpdateBlock = ^(CBCentralManager *central) {
        switch (central.state) {
            case CBCentralManagerStatePoweredOn:
                kAutoHideLoadingView(self.view, @"蓝牙已打开，并且可用",1)
                //                SHOW_HUD_AUTOHIDE(@"蓝牙已打开，并且可用");
                [central scanForPeripheralsWithServices:nil options:nil];
                [self addPrinter];
                break;
            case CBCentralManagerStatePoweredOff:
                kAutoHideLoadingView(self.view, @"蓝牙可用，未打开",1)
                //                SHOW_HUD_AUTOHIDE(@"蓝牙可用，未打开");
                break;
            case CBCentralManagerStateUnsupported:
                kAutoHideLoadingView(self.view, @"SDK不支持",1)
                //                SHOW_HUD_AUTOHIDE(@"SDK不支持");
                break;
            case CBCentralManagerStateUnauthorized:
                //                SHOW_HUD_AUTOHIDE(@"程序未授权");
                kAutoHideLoadingView(self.view, @"程序未授权",1)
                break;
            default:
                break;
        }
    };
    if (manager.centralManager.state == CBCentralManagerStatePoweredOn) {
        [manager scanForPeripheralsWithServiceUUIDs:nil options:nil];
        [self addPrinter];
    }
}

///连接打印机
- (void)connectPrint{
    HLBLEManager *manager = [HLBLEManager sharedInstance];
    kWeakSelf
    [manager connectPeripheral:_perpheral connectOptions:@{CBConnectPeripheralOptionNotifyOnDisconnectionKey:@(YES)}
        stopScanAfterConnected:YES servicesOptions:nil characteristicsOptions:nil completeBlock:^(HLOptionStage stage, CBPeripheral *peripheral, CBService *service, CBCharacteristic *character, NSError *error) {
            switch (stage) {
                case HLOptionStageConnection:
                {
                    if (error) {
                        kAutoHideLoadingView(self.view,@"连接失败",1);
                    } else {
                        kAutoHideLoadingView(self.view,@"连接成功",1);
                        //                        SHOW_HUD_AUTOHIDE(@"连接成功");
                        isConnection = YES;
                    }
                    break;
                }case HLOptionStageSeekServices:
                {
                    if (error) {
                        NSLog(@"查找服务失败");
                    } else {
                        NSLog(@"查找服务成功");
                        weakSelf.infos = [NSMutableArray array];
                        [weakSelf.infos addObjectsFromArray:peripheral.services];
                    }
                    break;
                }
                case HLOptionStageSeekCharacteristics:
                {
                    // 该block会返回多次，每一个服务返回一次
                    if (error) {
                        NSLog(@"查找特性失败");
                    } else {
                        NSLog(@"查找特性成功");
                    }
                    break;
                }
                case HLOptionStageSeekdescriptors:
                {
                    // 该block会返回多次，每一个特性返回一次
                    if (error) {
                        NSLog(@"查找特性的描述失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }];
}

///断开打印机
-(void)bleakBlueTooth{
    HLBLEManager *manager = [HLBLEManager sharedInstance];
    [manager cancelPeripheralConnection];
}

- (void)addPrinter{
    HLBLEManager *manager = [HLBLEManager sharedInstance];
    kWeakSelf
    manager.discoverPeripheralBlcok = ^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        if (peripheral.name.length <= 0) {
            return ;
        }
        if (self.deviceArray.count == 0) {
            NSDictionary *dict = @{@"peripheral":peripheral, @"RSSI":RSSI};
            [self.deviceArray addObject:dict];
        } else {
            BOOL isExist = NO;
            for (int i = 0; i < self.deviceArray.count; i++) {
                NSDictionary *dict = [self.deviceArray objectAtIndex:i];
                CBPeripheral *per = dict[@"peripheral"];
                if ([per.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
                    isExist = YES;
                    NSDictionary *dict = @{@"peripheral":peripheral, @"RSSI":RSSI};
                    [weakSelf.deviceArray replaceObjectAtIndex:i withObject:dict];
                }
            }
            
            if (!isExist) {
                NSDictionary *dict = @{@"peripheral":peripheral, @"RSSI":RSSI};
                [self.deviceArray addObject:dict];
            }
        }
        NSLog(@"蓝牙个数：%ld",(long)self.deviceArray.count);
        
        [self.tipsLabel removeFromSuperview];
        [self addPrintSubView];
        
        [self setPopWindowData];
    };
}

- (void)addPrintSubView{
    if ([_popWindow isDescendantOfView:self.view]) {
        return;
    }
    _popWindow = [[NSBundle mainBundle] loadNibNamed:@"PrintPopWindow" owner:nil options:nil].firstObject;
    _popWindow.frame = self.view.bounds;
    _popWindow.xButton.hidden = YES;
    
    kWeakSelf
    
    _popWindow.clickCell = ^(UITableViewCell *cell, NSInteger row){
        if (row <= 0 || weakSelf.deviceArray.count <= 0) {
            return ;
        }
        
        NSDictionary *dic = weakSelf.deviceArray[row-1];
        weakSelf.perpheral = dic[@"peripheral"];
        [weakSelf connectPrint];
    };
    
    _popWindow.closeBlock = ^{
        //        [weakSelf.view removeFromSuperview];
        [weakSelf bleakBlueTooth];
        [weakSelf removeFromParentViewController];
    };
    
    _pageTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, _popWindow.table.width - 10 - 180, 30)];
    _pageTextField.text = @"2";
    _pageTextField.keyboardType = UIKeyboardTypePhonePad;
    _pageTextField.layer.borderWidth = 1;
    // kAutoHideLoadingView(self.view,@"连接成功",1);
    _pageTextField.layer.borderColor = kHexColor(0xe1e1e1).CGColor;
    _pageTextField.inputAccessoryView = [HSTool getInputAccessoryViewForCloseKeyboard];
    
    
    [_popWindow.daYinButton addTarget:self action:@selector(print) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_popWindow];
}

- (void)setPopWindowData{
    
    UITableViewCell *pageCell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:nil];
    //    pageCell.textLabel.text = @"打印份数：";
    //    pageCell.accessoryView = _pageTextField;
    pageCell.textLabel.text = @"请选择打印机进行打印";
    pageCell.textLabel.textColor = [UIColor redColor];
    pageCell.textLabel.textAlignment = NSTextAlignmentRight;
    NSMutableArray *arr = [NSMutableArray arrayWithObject:pageCell];
    for (int i = 0;i < _deviceArray.count;i++) {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
        NSDictionary *dict = [self.deviceArray objectAtIndex:i];
        CBPeripheral *peripherral = dict[@"peripheral"];
        cell.textLabel.text = [NSString stringWithFormat:@"名称:%@",peripherral.name];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        [arr addObject:cell];
    }
    _popWindow.cells = arr;
}

- (void)print{
    if (!isConnection) {
        kAutoHideLoadingView(self.view,@"打印机尚未连接成功",1);
        return;
    }
    [self addPrintOverView];
    [_popWindow removeFromSuperview];
    
    NSLog(@"开始打印");
    
//    int page = [self.pageTextField.text intValue];
    
    [self printContent];
}


- (void)printContent{
    [self getCharacter];
    [self printInfo];
    [self printQuotePkg];
    [self printQuoteItem];
    [self printPrice];
    [self printFooter];
    [self addEmpty];
    [self isWriteSucess];
}

//获取特征值
- (void)getCharacter {
    for (CBService * service in _infos) {
        for (CBCharacteristic * character in service.characteristics) {
            CBCharacteristicProperties properties = character.properties;
            if (properties & CBCharacteristicPropertyWrite) {
                self.chatacter = character;
                return;
            }
        }
    }
}

//写入是否成功
-(void)isWriteSucess{
    NSData *mainData = [_printer getFinalData];
    HLBLEManager *bleManager = [HLBLEManager sharedInstance];
    //    [bleManager writeValue:mainData forCharacteristic:self.chatacter type:CBCharacteristicWriteWithoutResponse];
    
    if (self.chatacter.properties & CBCharacteristicPropertyWrite) {
        [bleManager writeValue:mainData forCharacteristic:self.chatacter type:CBCharacteristicWriteWithResponse completionBlock:^(CBCharacteristic *characteristic, NSError *error) {
            NSLog(@"错误：%@",error);
            if (!error) {
                NSLog(@"写入成功");
            }
        }];
    }
    //    else if (self.chatacter.properties & CBCharacteristicPropertyWriteWithoutResponse) {
    //        [bleManager writeValue:mainData forCharacteristic:self.chatacter type:CBCharacteristicWriteWithoutResponse];
    //    }
}

- (void)addEmpty{
    NSString *string = @"\n\n";
    [_printer appendText:string alignment:HLTextAlignmentCenter];
}

- (NSString *)addOnceText:(NSString *)text{
    int onceLength = text.chartLength;
    NSMutableString *string = [NSMutableString string];
    for (int i = 0; i < TOTAL/onceLength; i++) {
        [string appendString:text];
    }
    return string;
}


- (void)printInfo{
    [_printer appendText:_typeName ?:@"" alignment:(HLTextAlignmentCenter) fontSize:(HLFontSizeTitleMiddle)];

    NSString *quoteNo = [NSString stringWithFormat:@"工单号： %@",_data.kehuInfo.serviceCode?:@""];
    NSString *comName = [NSString stringWithFormat:@"门店名称： %@",_data.kehuInfo.compName?:@""];
    NSString *address = [NSString stringWithFormat:@"门店地址： %@",_data.kehuInfo.compAddress?:@""];
    NSString *tel = [NSString stringWithFormat:@"门店电话： %@",_data.kehuInfo.compTel?:@""];
    NSString *clientName = [NSString stringWithFormat:@"客户姓名： %@",_data.kehuInfo.guestFullName?:@""];
    NSString *vin = [NSString stringWithFormat:@"VIN： %@",_data.kehuInfo.vin?:@""];
    NSString *carNO = [NSString stringWithFormat:@"车牌号： %@",_data.kehuInfo.carNo?:@""];
    NSString *carModel = [NSString stringWithFormat:@"车型： %@",_data.kehuInfo.carModel?:@""];
    NSString *enterKilometers = [NSString stringWithFormat:@"里程： %@",_data.kehuInfo.enterKilometers?:@""];
    NSString *oil = [NSString stringWithFormat:@"油表信息： %@",_data.kehuInfo.enterOilMass?:@""];
    NSString *guestDesc = [NSString stringWithFormat:@"客户描述: %@", _data.kehuInfo.guestDesc ?:@""];
    NSString *faultPhen = [NSString stringWithFormat:@"故障描述: %@", _data.kehuInfo.faultPhen ?:@""];
    NSString *solveMethod = [NSString stringWithFormat:@"解决方案: %@", _data.kehuInfo.solveMethod ?:@""];

    [_printer setLineSpace:50];
    [_printer appendText:quoteNo alignment:(HLTextAlignmentLeft)];
    [_printer appendText:[self addOnceText:@"."] alignment:(HLTextAlignmentCenter)];
    
    [_printer appendText:comName alignment:(HLTextAlignmentLeft)];
    [_printer appendText:address alignment:(HLTextAlignmentLeft)];
    [_printer appendText:tel alignment:(HLTextAlignmentLeft)];
    [_printer appendText:clientName alignment:(HLTextAlignmentLeft)];
    [_printer appendText:carNO alignment:(HLTextAlignmentLeft)];
    [_printer appendText:vin alignment:(HLTextAlignmentLeft)];
    [_printer appendText:carModel alignment:(HLTextAlignmentLeft)];
    [_printer appendText:enterKilometers alignment:(HLTextAlignmentLeft)];
    [_printer appendText:oil alignment:(HLTextAlignmentLeft)];
    
    [_printer setLineSpace:30];
    [_printer appendText:[self addOnceText:@"."] alignment:(HLTextAlignmentCenter)];
    if (!kStringIsEmpty(_data.kehuInfo.guestDesc)){
        [_printer appendText:guestDesc alignment:(HLTextAlignmentLeft)];
        [_printer appendText:[self addOnceText:@"."] alignment:(HLTextAlignmentCenter)];
    }
    
    if (!kStringIsEmpty(_data.kehuInfo.faultPhen)){
        [_printer appendText:faultPhen alignment:(HLTextAlignmentLeft)];
        [_printer appendText:[self addOnceText:@"."] alignment:(HLTextAlignmentCenter)];
    }
    
    if (!kStringIsEmpty(_data.kehuInfo.solveMethod)){
        [_printer appendText:solveMethod alignment:(HLTextAlignmentLeft)];
        [_printer appendText:[self addOnceText:@"."] alignment:(HLTextAlignmentCenter)];
    }
}


- (void)printQuotePkg{
    
    NSArray *arr = _data.pkgList ?: @[];
    [_printer appendText:[self addOnceText:@"."] alignment:(HLTextAlignmentCenter)];
    [_printer appendText:@"套餐信息" alignment:(HLTextAlignmentCenter)];
     [_printer setLineSpace:40];
    [_printer appendText:[self addOnceText:@"."] alignment:(HLTextAlignmentCenter)];
    
    if (arr.count == 0) {
        return;
    }
    [_printer addLittleTitle:@"项目" value:@"金额"];
    for (QuotePkgData *item in arr) {
        NSString *pkgName = [NSString stringWithFormat:@"%@%@",item.packageName,[item.cardDetailId integerValue] ? @"(预存)":@""];
        [_printer addLittleTitle:pkgName value:item.amt ?:@""];
        for (QuoteItemData *itemModel in item.itemList ?: @[]) {// 工时
            [_printer addLittleTitle:[NSString stringWithFormat:@"工时:%@",itemModel.itemName ?:@""] value:itemModel.amt?:@""];
        }
        for (QuotePartData *part in item.partList ?: @[]) {// 配件
            [_printer addLittleTitle:[NSString stringWithFormat:@"配件:%@ X %@",part.partName ?:@"", part.qty?:@""] value:part.amt ?:@""];
        }
    }
    
}

- (void)printQuoteItem{
    [_printer setLineSpace:50];
    [_printer appendText:[self addOnceText:@"."] alignment:(HLTextAlignmentCenter)];
    [_printer appendText:@"工时信息" alignment:(HLTextAlignmentCenter)];
    [_printer setLineSpace:30];
    [_printer appendText:[self addOnceText:@"."] alignment:(HLTextAlignmentCenter)];
    
    [_printer appendLeftText:@"项目" middleText:@"金额" rightText:@"应收费用" isTitle:YES];
    
    NSArray *arr = _data.itemList ?: @[];
    if (arr.count == 0) {
        return;
    }
    
    for (QuoteItemData *itemModel in arr ?: @[]) {// 工时
        [_printer addLittleTitle:[NSString stringWithFormat:@"工时:%@",itemModel.itemName ?:@""] value:itemModel.amt ?:@""];

        [_printer appendText:[self addOnceText:@"."] alignment:(HLTextAlignmentCenter)];
    }
}

- (void)printPrice{
    [_printer appendText:[self addOnceText:@"."] alignment:(HLTextAlignmentCenter)];
    [_printer appendTitle:@"应收总计：" value:_data.kehuInfo.totalAmt?:@"" fontSize:(HLFontSizeTitleMiddle)];
    [_printer appendTitle:@"优惠总计：" value:_data.kehuInfo.discountAmt?:@"" fontSize:(HLFontSizeTitleMiddle)];
    [_printer appendTitle:@"实收总计：" value:_data.kehuInfo.subtotal?:@"" fontSize:(HLFontSizeTitleMiddle)];
    [_printer appendText:[self addOnceText:@"."] alignment:(HLTextAlignmentCenter)];
}

- (void)printFooter{
    [_printer setLineSpace:60];
    [_printer appendText:@"客户签字：" alignment:(HLTextAlignmentLeft)];
    
    [_printer appendText:[self addOnceText:@"."] alignment:(HLTextAlignmentCenter)];
    if (!kStringIsEmpty(_data.kehuInfo.repairEntrustPrintContent)) {
        [_printer appendText:_data.kehuInfo.repairEntrustPrintContent alignment:(HLTextAlignmentLeft)];
    }
    [_printer appendText:[self addOnceText:@"."] alignment:(HLTextAlignmentCenter)];

    [_printer setLineSpace:30];
   
    [_printer appendText: [NSString stringWithFormat:@"打印时间:%@",_data.kehuInfo.printTime ?:@""] alignment:(HLTextAlignmentCenter)];
}

@end
